package org.edu.modules.enroll.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.mapper.VeZsFenbanMapper;
import org.edu.modules.enroll.service.*;
import org.edu.modules.enroll.vo.VeZsFenbanExcelVo;
import org.edu.modules.enroll.vo.VeZsFenbanVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther 李少君
 * @Date 2021-07-24 10:36
 */
@Service
public class VeZsFenbanServiceImpl extends ServiceImpl<VeZsFenbanMapper, VeZsFenban> implements VeZsFenbanService {

    @Resource
    private VeZsFenbanMapper veZsFenbanMapper;
    @Resource
    private VeBaseManageServiceImpl veBaseManageService;
    @Resource
    private VeBaseGradeService veBaseGradeService;
    @Resource
    private VeBaseSpecialtyService veBaseSpecialtyService;
    @Resource
    private VeBaseFacultyService veBaseFacultyService;
    @Resource
    private VeBaseCampusService veBaseCampusService;

    //显示预分班表格
    @Override
    public HashMap<String, Object> getFenbanList(Integer gradeId, String enrollType,Integer falId, Integer specId, Integer statuId ,Integer currentPage, Integer pageSize) {
        Integer start = (currentPage - 1) * pageSize;
        List<VeZsFenbanVo> list = veZsFenbanMapper.getFenbanList(gradeId, enrollType,falId, specId, statuId,start,pageSize);
        Long count = veZsFenbanMapper.fenbanCount(gradeId, enrollType, falId, specId, statuId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("count",count);
        return map;
    }

    @Override
    public List<VeZsFenbanVo> getFenbanImport(Integer gradeId, String enrollType, Integer falId, Integer specId, Integer statuId) {
        return veZsFenbanMapper.getFenbanImport(gradeId, enrollType, falId, specId, statuId);
    }

    //为学生指定班级
    @Override
    public boolean giveBanji(Integer id, Integer banjiId) {
        return veZsFenbanMapper.giveBanji(id, banjiId);
    }

    //学生退班
    @Override
    public boolean exitBanji(Integer id) {
        return veZsFenbanMapper.exitBanji(id);
    }

    //(自动分班)查询计划人数分班表格
    @Override
    public List<VeZsFenbanVo> getZidongFenbanList(Integer gradeId, Integer specId, Integer falId,String enrollType) {
        return veZsFenbanMapper.getZidongFenbanList(gradeId, specId, falId, enrollType);
    }

    //计算总计划人数
    @Override
    public Integer jihuaNum(Integer gradeId, Integer specId, Integer falId,String enrollType) {
        return veZsFenbanMapper.jihuaNum(gradeId, specId, falId, enrollType);
    }

    //计算分班人数
    @Override
    public Integer fenbanNum(Integer specId,  Integer falId, Integer gradeId,String enrollType) {
        return veZsFenbanMapper.fenbanNum(specId, falId, gradeId, enrollType);
    }

    @Override
    public List<VeZsFenban> fenbanStu(Integer specId, String enrollType, Integer falId, Integer gradeId) {
        return veZsFenbanMapper.fenbanStu(specId, enrollType, falId, gradeId);
    }

    //自动分配班级
    @Override
    public boolean fenpeiBanji(Integer banjiId,Integer id) {
        return veZsFenbanMapper.fenpeiBanji(banjiId,id);
    }


//    //导入excel表格
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void excelImport(List<VeZsFenbanExcelVo> list) throws Exception {
//        //获取所有年级信息
//        BasicResponseBO<List<VeBaseGrade>> bo = veBaseManageService.getGradeAll();
//        List<VeBaseGrade> result1 = bo.getResult();
//        Map<String,Long> map1 = new HashMap<>() ;
//        result1.forEach(l-> map1.put(l.getNjmc(),l.getId()));
//        //获取所有校区信息
//        BasicResponseBO<List> bo1 = veBaseManageService.getCampusMessage();
//        List<VeBaseCampus> result2 = JSONObject.parseArray(JSON.toJSONString(bo1.getResult()),VeBaseCampus.class);
//        Map<String,Long> map2 = new HashMap<>() ;
//        result2.forEach(l-> map2.put(l.getXqmc(),l.getId()));
//        //获取所有专业信息
//        List<VeBaseSpecialty> result3 = veZsFenbanMapper.getZy();
//        Map<String,Long> map3 = new HashMap<>() ;
//        result3.forEach(l-> map3.put(l.getZymc(),l.getId()));
//
//        //字典
//        Map<String,Integer> dictMap = new HashMap<>() ;
//        dictMap.put("未分配",0);
//        dictMap.put("已分配",1);
//
//        int t = 5;
//        try{
//            for ( VeZsFenbanExcelVo ve : list) {
//                VeZsFenban fenban = new VeZsFenban();
//                BeanUtils.copyProperties(ve, fenban);
////                fenban.setXm(ve.getXm()).setXh(ve.getXh());
//                //获取年级id
//                Long gradeId = map1.get(ve.getGrade());
//                //获取校区id
//                Long xiaoquId = map2.get(ve.getCampus());
//                //获取专业id
//                Long zyId = map3.get(ve.getSpec());
//
//                fenban.setXm(ve.getXm()).setXh(ve.getXh()).setGradeId(gradeId.intValue()).
//                        setMark(ve.getMark()).setEnrollType(ve.getEnrollType()).setLuqu(ve.getLuqu())
//                        .setCampusId(xiaoquId.intValue()).setSpecId(zyId.intValue()).setStatuId(dictMap.getOrDefault(ve.getState(),0));
//
//                veZsFenbanMapper.insert(fenban);
//                t++;
//            }
//
//
//        }catch (Exception e){
//            throw new Exception("第"+t+"行数据有误！") ;
//        }
//
//    }

    @Override
    public List<VeZsFenbanVo> getBanjiMessage(Integer gradeId, Integer specId) {
        return veZsFenbanMapper.getBanjiMessage(gradeId, specId);
    }

    @Override
    public HashMap<String, Object> zidongFenbanList(Integer gradeId, String enrollType, Integer falId, Integer specId,  Integer currentPage, Integer pageSize) {
        Integer start = (currentPage - 1) * pageSize;
        List<VeZsFenbanVo> list = veZsFenbanMapper.zidongFenbanList(specId, enrollType, falId, gradeId, start, pageSize);
        Integer count = veZsFenbanMapper.zidongFenbanNum(specId, enrollType, falId, gradeId, start, pageSize);
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("count",count);
        return map;
    }

    @Override
    public List<VeZsFenban> getStuMessage(String xm, String xh, String sfzh) {
        return veZsFenbanMapper.getStuMessage(xm, xh, sfzh);
    }

    //学生分班信息导入excel表格
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String excelImport(List<VeZsFenbanExcelVo> list) throws Exception {
        List<VeZsFenban> result = new ArrayList<>();
        //获取所有年级信息
//        BasicResponseBO<List<VeBaseGrade>> bo = veBaseManageService.getGradeAll();
//        List<VeBaseGrade> result1 = bo.getResult();
        List<VeBaseGrade> result1 = veBaseGradeService.list();//2021.9.2
                //获取所有校区信息
//        BasicResponseBO<List> bo1 = veBaseManageService.getCampusMessage();
//        List<VeBaseCampus> result2 = JSONObject.parseArray(JSON.toJSONString(bo1.getResult()),VeBaseCampus.class);
        List<VeBaseCampus> result2 = veBaseCampusService.list();//2021.9.2
                //获取所有专业部信息
//        BasicResponseBO<List<VeBaseFaculty>> bo2 = veBaseManageService.getFacultyAll();
//        List<VeBaseFaculty> result4 = bo2.getResult();
        List<VeBaseFaculty> result4 = veBaseFacultyService.list();//2021.9.2
                //获取所有专业信息
        List<VeBaseSpecialty> result3 = veZsFenbanMapper.getZy();
        //获取所有民族
        List<SysDictItem> mz = veZsFenbanMapper.getMz();
        //获取所有学制
        List<VeDictXuezi> xuezi = veZsFenbanMapper.getXuezi();
        //获取所有省
        List<VeDictArea> sheng = veZsFenbanMapper.getSheng(0);
        //获取管理员
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取所有分班信息
        List<VeZsFenban> fenban = veZsFenbanMapper.getFenbanMessage();
//        String admin = user.getId();
        List<String> collect1 = list.stream().map(VeZsFenbanExcelVo::getSfzh).distinct().collect(Collectors.toList());
        if(collect1.size()!=list.size()){
            return "导入的数据中存在相同身份证号的学生，请重新输入";
        }
        List<String> collect2 = list.stream().map(VeZsFenbanExcelVo::getXh).distinct().collect(Collectors.toList());
        if(collect2.size()!=list.size()){
            return "导入的数据中存在相同学号的学生，请重新输入";
        }
        List<String> collect3 = list.stream().map(VeZsFenbanExcelVo::getKsh).distinct().collect(Collectors.toList());
        if(collect3.size()!=list.size()){
            return "导入的数据中存在相同考生号的学生，请重新输入";
        }
        List<String> collect4 = list.stream().map(VeZsFenbanExcelVo::getBmh).distinct().collect(Collectors.toList());
        if(collect4.size()!=list.size()){
            return "导入的数据中存在相同报名号的学生，请重新输入";
        }
//        List<String> collect5 = list.stream().map(VeZsFenbanExcelVo::getZkzh).distinct().collect(Collectors.toList());
//        if(collect5.size()!=list.size()){
//            return "导入的数据中存在相同准考证号的学生，请重新输入";
//        }
        for (int i = 0;i<list.size();i++){
            for (int q = 0;q<list.size();q++) {


                for (int w = 0;w<fenban.size();w++){
                    if(list.get(q).getSfzh().equals(fenban.get(w).getSfzh())){
                        return "第" + (q + 4) + "行已存在该身份证号的学生，请重新输入";
                    }
                    if(list.get(q).getXh().equals(fenban.get(w).getXh())){
                        return "第" + (q + 4) + "行已存在该学号的学生，请重新输入";
                    }
                    if(list.get(q).getKsh().equals(fenban.get(w).getKsh())){
                        return "第" + (q + 4) + "行已存在该考生号的学生，请重新输入";
                    }
                    if(list.get(q).getBmh().equals(fenban.get(w).getBmh())){
                        return "第" + (q + 4) + "行已存在该报名号的学生，请重新输入";
                    }
//                    if(list.get(q).getZkzh().equals(fenban.get(w).getZkzh())){
//                        return "第" + (q + 4) + "行已存在该准考证号的学生，请重新输入";
//                    }
                }
            }



            VeZsFenban veZsFenban = new VeZsFenban();
            veZsFenban.setKsh(list.get(i).getKsh()).setXm(list.get(i).getXm()).setSfzh(list.get(i).getSfzh())
                    .setCsny(list.get(i).getCsny()).setZxmc(list.get(i).getZxmc()).setYzbm(list.get(i).getYzbm())
                    .setYjdz(list.get(i).getYjdz()).setYb(list.get(i).getYb()).setLxdh1(list.get(i).getLxdh1())
                    .setLxdh2(list.get(i).getLxdh2()).setTdcj(list.get(i).getTdcj()).setZy(list.get(i).getZy())
                    .setLqzy(list.get(i).getLqzy()).setJjr(list.get(i).getJjr()).setJjrdh(list.get(i).getJjrdh())
                    .setJjrdz(list.get(i).getJjrdz()).setSjr(list.get(i).getSjr()).setSjrjtdz(list.get(i).getSjrjtdz())
                    .setYjh(list.get(i).getYjh()).setZl(list.get(i).getZl()).setRxny(list.get(i).getRxny())
                    .setEnrollType(list.get(i).getEnrollType()).setLuqu(list.get(i).getLuqu())
                    .setStatuId(0).setBmh(list.get(i).getBmh()).setXh(list.get(i).getXh());

            if("男".equals(list.get(i).getXb())){
                veZsFenban.setXb("0");
            }else if("女".equals(list.get(i).getXb())){
                veZsFenban.setXb("1");
            }else {
                return "导入失败,请输入正确的性别";
            }
//            if("住校".equals(list.get(i).getJdfs())){
//                veZsFenban.setJdfs(1);
//            }else if("走读".equals(list.get(i).getJdfs())){
//                veZsFenban.setJdfs(2);
//            }else {
//                return "导入失败,请输入正确的就读方式";
//            }
//            if("是".equals(list.get(i).getSfskns())){
//                veZsFenban.setSfkns(1);
//            }else if("否".equals(list.get(i).getSfskns())){
//                veZsFenban.setSfkns(0);
//            }else {
//                return "导入失败,请输入是或否";
//            }
//            民族
            for (int l = 0; l < mz.size(); l++) {
                if (list.get(i).getMz().equals(mz.get(l).getItemText())) {
                    veZsFenban.setMzm(mz.get(l).getDictId());
                    break;
                }
            }
            if("".equals(veZsFenban.getMzm())){
                return "数据库中不存在该民族,请重新输入!";
            }
            //学制
            for (int m = 0; m < xuezi.size(); m++) {
                if(list.get(i).getXz().equals(xuezi.get(m).getXzmc())){
                    veZsFenban.setXz(xuezi.get(m).getId());
                    break;
                }
            }
            if("".equals(veZsFenban.getXz())){
                return "数据库中不存在该学制,请重新输入!";
            }
            //省市区
            for (int n = 0; n < sheng.size(); n++) {
                if(list.get(i).getProvince().equals(sheng.get(n).getName())){
                    veZsFenban.setProvince(sheng.get(n).getName()).setProvinceId(sheng.get(n).getId().intValue());
                    //通过省获取市
                    List<VeDictArea> shi = veZsFenbanMapper.getSheng(sheng.get(n).getId().intValue());
                    for (int b = 0;b<shi.size();b++){
                        if(list.get(i).getCity().equals(shi.get(b).getName())){
                            veZsFenban.setCity(shi.get(b).getName()).setCityId(shi.get(b).getId().intValue());
                            //通过市获取区
                            List<VeDictArea> qu = veZsFenbanMapper.getSheng(shi.get(b).getId().intValue());
                            for (int v = 0;v<qu.size();v++){
                                if(list.get(i).getCounty().equals(qu.get(v).getName())){
                                    veZsFenban.setCounty(qu.get(v).getName()).setCountyId(qu.get(v).getId().intValue());
                                }
                            }
                            if("".equals(veZsFenban.getCounty())){
                                return "数据库中不存在该区,请重新输入!";
                            }
                        }
                    }
                    if("".equals(veZsFenban.getCity())){
                        return "数据库中不存在该市,请重新输入!";
                    }

                }

            }
            if("".equals(veZsFenban.getProvince())){
                return "数据库中不存在该省,请重新输入!";
            }
            //生源地省市区
//            for (int n = 0; n < sheng.size(); n++) {
//                if(list.get(i).getProvince().equals(sheng.get(n).getName())){
//                    veZsFenban.setShengId(sheng.get(n).getId().intValue());
//                    //通过省获取市
//                    List<VeDictArea> shi = veZsFenbanMapper.getSheng(sheng.get(n).getId().intValue());
//                    for (int b = 0;b<shi.size();b++){
//                        if(list.get(i).getCity().equals(shi.get(b).getName())){
//                            veZsFenban.setShiId(shi.get(b).getId().intValue());
//                        }
//                        //通过市获取区
//                        List<VeDictArea> qu = veZsFenbanMapper.getSheng(shi.get(b).getId().intValue());
//                        for (int v = 0;v<qu.size();v++){
//                            if(list.get(i).getCounty().equals(qu.get(v).getName())){
//                                veZsFenban.setQuId(qu.get(v).getId().intValue());
//                            }
//                        }
//                        if("".equals(veZsFenban.getQuId())){
//                            return "数据库中不存在该区,请重新输入!";
//                        }
//                    }
//                    if("".equals(veZsFenban.getShiId())){
//                        return "数据库中不存在该市,请重新输入!";
//                    }
//
//                }
//
//            }
//            if("".equals(veZsFenban.getShengId())){
//                return "数据库中不存在该省,请重新输入!";
//            }



            for (int j=0;j<result1.size();j++){
                if (result1.get(j).getNjmc().equals(list.get(i).getGrade())){
                    veZsFenban.setGradeId(result1.get(j).getId().intValue());
                }
            }
            for (int k=0;k<result2.size();k++){
                if (result2.get(k).getXqmc().equals(list.get(i).getCampus())){
                    veZsFenban.setCampusId(result2.get(k).getId().intValue());
                }
            }
            //获取专业部
            for (int p = 0;p<result4.size();p++){
                if(result4.get(p).getYxmc().equals(list.get(i).getFaculty())){
                    veZsFenban.setFalId(result4.get(p).getId().intValue());
                }
            }
            if(veZsFenban.getFalId()==null){
                return "数据库中无该专业部!,请修改";
            }
            //根据专业部获取专业
//            BasicResponseBO<List<VeBaseSpecialty>> bo3 = veBaseManageService.getSpecialtyByFalId(veZsFenban.getFalId().longValue());
//            List<VeBaseSpecialty> result5 = bo3.getResult();
            QueryWrapper<VeBaseSpecialty> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("falId",veZsFenban.getFalId().longValue());
            List<VeBaseSpecialty> result5 = veBaseSpecialtyService.list(queryWrapper);//2021.9.2
            for (int u = 0; u < result5.size(); u++) {
                if(result5.get(u).getZymc().equals(list.get(i).getSpec())){
                    veZsFenban.setSpecId(result5.get(u).getId().intValue());
                }
            }
            //
//            for (int z=0;z<result3.size();z++){
//                if (result3.get(z).getZymc().equals(list.get(i).getSpec())){
//                    veZsFenban.setSpecId(result3.get(z).getId().intValue());
//                }
//            }
            if (veZsFenban.getSpecId() == null || veZsFenban.getCampusId() == null || veZsFenban.getGradeId() == null) {
                return "导入失败,请检查所填年级、校区、专业是否存在!";
            }
            result.add(veZsFenban);
        }
        //字典
        for ( VeZsFenban ve : result) {
            veZsFenbanMapper.importFenBan(ve);
        }
        return "导入成功";

    }

}
